import yt_dlp
import os

def progress_hook(d):
    if d['status'] == 'downloading':
        percent = d.get('_percent_str', '').strip()
        speed = d.get('_speed_str', '').strip()
        eta = d.get('_eta_str', '').strip()
        total = d.get('_total_bytes_str', d.get('_total_bytes_estimate_str', '???'))
        downloaded = d.get('_downloaded_bytes_str', '???')
        print(f"\r🔽 下载中: {percent} ({downloaded}/{total}) at {speed}, ETA: {eta}", end="")
    elif d['status'] == 'finished':
        print("\n✅ 下载完成，正在合并视频和音频...")

def download_youtube_video(url, output_dir="downloads"):
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    ydl_opts = {
        'outtmpl': f'{output_dir}/%(title)s.%(ext)s',
        'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',
        'merge_output_format': 'mp4',
        'quiet': True,
        'noplaylist': True,
        'progress_hooks': [progress_hook],
        'nocheckcertificate': True,
        'force_ipv4': True,
        'http_headers': {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
                          '(KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
        },
        # 如果有 cookies 文件也可以加上这一行
        'cookiefile': 'cookies.txt',
        'writesubtitles': True,  # 下载自动生成的字幕
        'subtitleslangs': ['zh'],  # 下载中文字幕
    }

    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        ydl.download([url])

# 示例：替换成你要下载的视频地址
video_url = input("请输入 YouTube 视频链接：")
download_youtube_video(video_url)
